<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot-scope="scope" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.tenant_view" @click.stop="handleView(scope.row, scope.index)">查 看</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.tenant_edit && (scope.row.tenantAuditStatus == 0 || scope.row.tenantAuditStatus == 3)" @click.stop="handleEdit(scope.row, scope.index)">编 辑</el-button>
        <el-button icon="el-icon-menu" size="small" type="text" v-if="scope.row.tenantAuditStatus == 2" @click.stop="handleMenu(scope.row, scope.index)">菜单分配</el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" v-if="permission.tenant_add" @click.stop="handleSave">新 增</el-button>
        <!-- <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.tenant_delete"
                   plain
                   @click="handleDelete">删 除
        </el-button> -->
<!--        <el-tooltip class="item" effect="dark" content="给租户配置账号额度、过期时间等授权信息" placement="top">-->
<!--          <el-button size="small"-->
<!--                     plain-->
<!--                     v-if="userInfo.role_name.includes('administrator')"-->
<!--                     icon="el-icon-setting"-->
<!--                     @click="handleSetting">授权配置-->
<!--          </el-button>-->
<!--        </el-tooltip>-->
<!--        <el-tooltip class="item" effect="dark" content="给租户配置独立数据源以实现数据库隔离" placement="top">-->
<!--          <el-button size="small"-->
<!--                     plain-->
<!--                     v-if="userInfo.role_name.includes('administrator')"-->
<!--                     icon="el-icon-coin"-->
<!--                     @click="handleDatasource">数据源配置-->
<!--          </el-button>-->
<!--        </el-tooltip>-->
<!--        <el-tooltip class="item" effect="dark" content="将菜单产品包与租户配置绑定" placement="top">-->
<!--          <el-button size="small"-->
<!--                     plain-->
<!--                     v-if="userInfo.role_name.includes('administrator')"-->
<!--                     icon="el-icon-notebook-1"-->
<!--                     @click="handlePackage">产品包配置-->
<!--          </el-button>-->
<!--        </el-tooltip>-->
<!--        <el-tooltip class="item" effect="dark" content="将自定义的菜单集合定制为租户绑定的菜单产品包" placement="top">-->
<!--          <el-button size="small"-->
<!--                     plain-->
<!--                     v-if="userInfo.role_name.includes('administrator')"-->
<!--                     icon="el-icon-notebook-2"-->
<!--                     @click="handlePackageSetting">产品包管理-->
<!--          </el-button>-->
<!--        </el-tooltip>-->
      </template>
      <template slot-scope="{row}"
                slot="accountNumber">
        <el-tag>{{ row.accountNumber > 0 ? row.accountNumber : '不限制' }}</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="expireTime">
        <el-tag>{{ row.expireTime ? row.expireTime : '不限制' }}</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="isCooperate">
        <el-tag>{{ row.isCooperateName }}</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="profitState">
        <el-tag>{{ row.profitStateName }}</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="cooperateState">
        <el-tag>{{ row.cooperateStateName }}</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="tenantAuditStatus">
        <el-tag type="success" :color="getColorTenantAuditStatus(row.tenantAuditStatus)" effect="dark">{{ row.tenantAuditStatusName }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog
      :title="dialogText+'租户'"
      top="1%"
      :width="screenWidth>1920?'60%':(screenWidth<=1920 && screenWidth>1500)?'80%':'90%'"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose">
      <div class="dialog-menu">
        <el-steps :active="active" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="实名信息"></el-step>
          <el-step title="结算卡信息"></el-step>
          <el-step title="分配通道"></el-step>
          <el-step title="分润配置"></el-step>
          <el-step title="预览提交"></el-step>
        </el-steps>
        <el-divider></el-divider>
      </div>

      <div class="el-dialog-div" v-show="active == 0">
        <basic-form :basicForm="basicForm" ref="toBasicForm" />
      </div>
      <template>
        <div v-show="active == 1">
          <main-form :mainForm="mainForm" ref="toMainForm" />
        </div>
      </template>
      <template>
        <div v-show="active == 2">
          <card-form :cardForm="cardForm" ref="toCardForm" />
        </div>
      </template>
      <template>
        <div v-show="active == 3">
          <el-transfer
            class="tenant-flex"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入通道名称"
            :button-texts="['取消分配', '分配通道']"
            :titles="['未分配通道', '已分配通道']"
            v-model="aisleAllot"
            :data="aisleData">
          </el-transfer>
        </div>
      </template>
      <template v-if="active == 4">
        <policy-form :oem="oem" ref="toPolicyForm" />
      </template>
      <template v-if="active == 5">
        <oem-preview :tenantData="tenantData" />
      </template>

      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-top" size="small" type="primary" v-preventClick @click="handlePageUp" v-if="active != 0">上一页</el-button>
        <el-button :icon="dialogSubmitBtnText == '下一页'?'el-icon-bottom':'el-icon-check'" size="small" v-preventClick @click="handlePageDown">{{dialogSubmitBtnText}}</el-button>
      </span>
    </el-dialog>
    <el-dialog title="租户菜单分配"
               append-to-body
               :visible.sync="dialogMenuVisible"
               width="450px">
      <menu-grant ref="toMenuGrant" />
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogMenuVisible = false">取 消</el-button>
        <el-button size="small" type="primary" v-preventClick @click="menuSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <el-dialog title="租户授权配置"
               append-to-body
               :visible.sync="box"
               width="450px">
      <avue-form :option="settingOption" v-model="settingForm" @submit="handleSubmit"/>
    </el-dialog>
    <el-dialog title="租户数据源配置"
               append-to-body
               :visible.sync="datasourceBox"
               width="450px">
      <avue-form :option="datasourceOption" v-model="datasourceForm" @submit="handleDatasourceSubmit"/>
    </el-dialog>
    <el-dialog title="租户产品包配置"
               append-to-body
               :visible.sync="packageBox"
               width="450px">
      <avue-form ref="formPackage" :option="packageOption" v-model="packageForm" @submit="handlePackageSubmit"/>
    </el-dialog>
    <el-dialog title="租户产品包管理"
               append-to-body
               :visible.sync="packageSettingBox"
               width="1000px">
      <tenant-package></tenant-package>
    </el-dialog> -->
  </basic-container>
</template>

<script>
import {getList, getDetail, getAuthDetail, getBankDetail, getAisleAllList, getAisleOemList, remove, update, authUpdate, bankUpdate, aisleUpdate, oemPolicyUpdate, add, authAdd, bankAdd, aisleAdd, oemPolicyAdd, getFinish, getTenantDetail, setting, datasource, packageInfo, packageSetting} from "@/api/system/tenant";
import { getRegion } from "@/api/system/dict";
import {getDetail as packageDetail} from "@/api/system/tenantpackage";
import {getRole, grantTree} from "@/api/system/role";
import {mapGetters} from "vuex";
import {getMenuTree, submitMenu} from "@/api/system/menu";
import {validatenull, isMobile} from "@/util/validate";
import basicForm from '@/components/rb-core/basic-form';
import mainForm from '@/components/rb-core/main-form';
import cardForm from '@/components/rb-core/card-form';
import policyForm from '@/components/rb-core/policy-form';
import oemPreview from '@/components/rb-core/oem-preview';
import menuGrant from '@/components/rb-core/menu-grant';
// import exForm from '@/views/plugin/workflow/mixins/ex-form'

export default {
  // mixins: [exForm],
  components: {
    basicForm,
    mainForm,
    cardForm,
    policyForm,
    oemPreview,
    menuGrant
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else if (!isMobile(value)) {
        callback(new Error('手机号码不正确！'));
      } else {
        callback();
      }
    };
    return {
      screenWidth: document.documentElement.clientWidth,
      form: {},
      file: {},
      dialogMenuVisible: false,
      dialogVisible: false,
      dialogType: '', //打开类型 add/edit
      dialogText: '',
      dialogSubmitBtnText: '下一页',
      active: 0,
      props: { //菜单权限数据 props
        label: "title",
        value: "key",
      },
      selectionList: [],
      query: {},
      loading: true,
      oem: {
        tenantId: "",
        userNo: "",
        userType: '1',
      },
      box: false,
      datasourceBox: false,
      packageBox: false,
      packageSettingBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        dialogWidth: 900,
        dialogClickModal: false,
        column: [
          {
            label: "租户ID",
            prop: "tenantId",
            width: 100,
            addDisplay: false,
            editDisplay: false,
            span: 24,
            hide: true,
            overHidden: true,
          },
          {
            label: "租户编号",
            prop: "tenantCode",
            slot: true,
            display: false,
            width:200,
            overHidden: true,
          },
          {
            label: "租户名称",
            prop: "tenantName",
            search: true,
            span: 12,
            width:200,
            overHidden: true,
          },
          {
            label: "租户类型",
            prop: "tenantType",
            type: "select",
            dataType: "number",
            showColumn: false,
            slot: true,
            hide: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=tenant_type',
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            overHidden: true,
          },
          {
            label: "租户类型",
            prop: "tenantTypeName",
            slot: true,
            width: 90,
            display: false,
            overHidden: true,
          },
          {
            label: "联系人",
            prop: "linkman",
            search: true,
            rules: [{
              required: true,
              message: "请输入联系人",
              trigger: "blur"
            }],
            overHidden: true,
          },
          {
            label: "联系电话",
            prop: "contactNumber",
            search: true,
            rules: [{
              required: true,
              trigger: "blur",
              validator: validatePhone
            }],
            overHidden: true,
            width:150,
          },
          {
            label: '省份/地市/区县',
            labelWidth: 130,
            prop: 'provinceCityArea',
            type: 'cascader',
            props: {
              label: 'name',
              value: 'code'
            },
            lazy: true,
            lazyLoad(node, resolve) {
              let stop_level = 2;
              let level = node.level;
              let data = node.data || {}
              let code = data.code;
              let list = [];
              let callback = () => {
                resolve((list || []).map(ele => {
                  return Object.assign(ele, {
                    leaf: level >= stop_level
                  })
                }));
              }
              if (level == 0) {
                getRegion(code).then(res => {
                  list = res.data.data;
                  callback()
                }, error => {
                  window.console.log(error);
                })
              }else if (level == 1) {
                getRegion(code).then(res => {
                  list = res.data.data;
                  callback()
                }, error => {
                  window.console.log(error);
                })
              } else if (level == 2) {
                getRegion(code).then(res => {
                  list = res.data.data;
                  callback()
                }, error => {
                  window.console.log(error);
                })
              }else{
                 callback()
              }
            },
            span: 24,
            showColumn: false,
            hide: true,
            rules: [{
              required: true,
              message: "请选择省份/地市/区县",
              trigger: "blur"
            }],
            overHidden: true,
          },
          {
            label: '省份',
            prop: 'provinceName',
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: '地市',
            prop: 'cityName',
            slot: true,
            display: false
          },
          {
            label: '区县',
            prop: 'areaName',
            slot: true,
            display: false,
            overHidden: true
          },
          {
            label: "联系地址",
            prop: "address",
            span: 24,
            minRows: 2,
            type: "textarea",
            hide: true,
            rules: [{
              required: true,
              message: "请输入联系地址",
              trigger: "blur"
            }],
            overHidden: true
          },
          {
            label: '邮箱',
            prop: 'email',
            slot: true,
            display: false,
            width:150,
            overHidden: true
          },
          {
            label: "绑定域名",
            prop: "domain",
            span: 24,
            prepend:'https://',
            append:'com',
            width:200,
            overHidden: true
          },
          {
            label: "系统背景",
            prop: "backgroundUrl",
            type: 'upload',
            listType: 'picture-img',
            dataType: 'string',
            action: '/api/blade-resource/oss/endpoint/put-file',
            propsHttp: {
              res: 'data',
              url: 'link',
            },
            hide: true,
            span: 24,
            overHidden: true
          },
          // {
          //   label: "账号额度",
          //   prop: "accountNumber",
          //   width: 90,
          //   slot: true,
          //   addDisplay: false,
          //   editDisplay: false,
          // },
          // {
          //   label: "过期时间",
          //   prop: "expireTime",
          //   width: 160,
          //   slot: true,
          //   span: 24,
          //   addDisplay: false,
          //   editDisplay: false,
          // },
          {
            label: "异常状态原因",
            width: 150,
            labelWidth: 120,
            prop: "exceptionMsg",
            span: 12,
            overHidden: true
          },
          {
            label: "合作状态",
            prop: "isCooperate",
            span: 24,
            type: "switch",
            width: 100,
            dicUrl: "/api/blade-system/dict/dictionary?code=is_cooperate",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            value: '1',
            dataType: 'string',
            slot: true,
            addDisplay: false,
            hide: true,
            overHidden: true
          },
          {
            label: "分润状态",
            prop: "profitState",
            span: 12,
            type: "radio",
            width: 100,
            dicUrl: "/api/blade-system/dict/dictionary?code=profit_state",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            value: '2',
            dataType: 'string',
            slot: true,
            addDisplay: false,
            hide: true,
            overHidden: true
          },
          {
            label: "合同状态",
            prop: "cooperateState",
            span: 12,
            type: "radio",
            width: 110,
            dicUrl: "/api/blade-system/dict/dictionary?code=cooperate_state",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            value: '0',
            dataType: 'string',
            slot: true,
            addDisplay: false,
            hide: true,
            overHidden: true
          },
          {
            label: "审核状态",
            prop: "tenantAuditStatus",
            span: 12,
            type: "select",
            width: 110,
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=tenant_audit_status",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: 'string',
            slot: true,
            display: false,
            overHidden: true
          },
          // {
          //   label: "审核备注",
          //   prop: "auditResult",
          //   width: 150,
          //   span: 24,
          //   addDisplay: false,
          //   editDisplay: false,
          // },
          {
            label: "审核时间",
            prop: "auditTime",
            width: 150,
            slot: true,
            span: 24,
            addDisplay: false,
            editDisplay: false,
            overHidden: true
          },
          {
            label: "创建时间",
            prop: "createTime",
            width: 150,
            slot: true,
            span: 24,
            addDisplay: false,
            editDisplay: false,
            overHidden: true
          },
          // {
          //   prop:'ids',
          //   span: 24,
          //   labelWidth: 0,
          //   formslot: true,
          //   showColumn: false,
          //   slot: true,
          //   hide: true
          // },
        ]
      },
      data: [],
      basicForm: {
        id: '',
        tenantName: '',
        tenantType: '',
        linkman: '',
        contactNumber: '',
        province: '',
        city: '',
        area: '',
        address: '',
        email: '',
        isCooperate: '1',
        profitState: '2',
        cooperateState: '0',
        domain: '',
        logo: '',
        backgroundUrl: '',
      },
      mainForm: {
        compName: '',
        roaName: '',
        roaCardNo: '',
        roaLicenseNo: '',
        roaLicenseTime: '',
        roaLicenseImage: '',
        roaCardPositive: '',
        roaCardBack: '',
        roaCardTime: '',
      },
      cardForm: {
        robBank: '',
        robBankBranch: '',
        robBankName: '',
        robUnionNumber: '',
        robBankNo: '',
        // robBankPositive: '',
        // robBankBack: '',
        robCardPublicImg: '',
      },
      // policyForm: {
      //   polName: '',
      //   polType: '',
      //   polCategory: '',
      //   polKind: '',
      // },
      aisleAllot: [], //通道分配 绑定value
      aisleData: [], //通道分配 数据
      tenantData: [], //租户六合一 数据
      settingForm: {},
      settingOption: {
        column: [
          {
            label: "账号额度",
            prop: "accountNumber",
            type: "number",
            span: 24,
          },
          {
            label: "过期时间",
            prop: "expireTime",
            type: "date",
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd hh:mm:ss",
            span: 24,
          }
        ]
      },
      datasourceForm: {},
      datasourceOption: {
        column: [
          {
            label: "数据源",
            prop: "datasourceId",
            search: true,
            span: 24,
            type: "select",
            dicUrl: "/api/blade-develop/datasource/select",
            props: {
              label: "name",
              value: "id"
            },
            rules: [{
              required: true,
              message: "请选择数据源",
              trigger: "blur"
            }]
          },
        ]
      },
      packageForm: {},
      packageOption: {
        column: [
          {
            label: "产品包",
            prop: "packageId",
            search: true,
            span: 24,
            type: "select",
            dicUrl: "/api/blade-system/tenant-package/select",
            props: {
              label: "packageName",
              value: "id"
            },
            rules: [{
              required: true,
              message: "请选择产品包",
              trigger: "blur"
            }]
          },
          {
            label: "菜单预览",
            prop: "menuId",
            span: 24,
            type: "tree",
            dicData: [],
            hide: true,
            multiple: true,
            props: {
              label: "title"
            },
          },
        ]
      },
    };
  },
  watch: {
    'packageForm.packageId'() {
      if (!validatenull(this.packageForm.packageId)) {
        packageDetail(this.packageForm.packageId).then(res => {
          this.packageForm.menuId = res.data.data.menuId;
          this.initData();
        });
      }
    }
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.tenant_add, false),
        viewBtn: this.vaildData(this.permission.tenant_view, false),
        delBtn: this.vaildData(this.permission.tenant_delete, false),
        editBtn: this.vaildData(this.permission.tenant_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    tenantId() {
      return this.selectionList[0].tenantId;
    },
    getColorTenantAuditStatus() {
      return state => {
        if (state == '0') {
          return '#E6A23C';
        } else if (state == '1') {
          return '#396afc';
        } else if (state == '2') {
          return '#67C23A';
        } else if (state == '3') {
          return '#F56C6C';
        }
      }
    },
  },
  methods: {
    initData() {
      getMenuTree().then(res => {
        const column = this.findObject(this.packageOption.column, "menuId");
        column.dicData = res.data.data;
      });
    },
    /**
     * @func 上一页
     * @desc OEM租户六合一表单 上一页
     * */
    handlePageUp() {
      if (this.active-- <= 0) this.active = 0;
      this.dialogSubmitBtnText = '下一页';
      switch (this.active) {
        case 0:
          getDetail(this.oem.id).then((res) => {
            this.basicForm.id = res.data.data.id;
          });
          break;
        case 1:
          getAuthDetail(this.oem.tenantId, this.oem.userNo, this.oem.userType).then(res => {
            this.mainForm.id = res.data.data.id;
          });
          break;
        case 2:
          getBankDetail(this.oem.tenantId, this.oem.userNo, this.oem.userType).then(res => {
            this.cardForm.id = res.data.data.id;
          });
          break;
      }
    },
    /**
     * @func 下一页
     * @desc OEM租户六合一表单 下一页
     * */
    handlePageDown() {
      const _this = this;
      switch (_this.active) {
        case 0:
          _this.basicSubmit(_this.dialogType);
          break;
        case 1:
          _this.mainSubmit(_this.dialogType);
          break;
        case 2:
          _this.cardSubmit(_this.dialogType);
          break;
        case 3:
          _this.aisleSubmit(_this.dialogType);
          break;
        case 4:
          _this.oemPolicySubmit(_this.dialogType);
          break;
        case 5:
          _this.emptyForm();
          _this.$message({
            type: "success",
            message: "OEM 租户信息提交成功!"
          });
          _this.dialogVisible = false;
          _this.onLoad(_this.page);
          break;
      }
    },
    /**
     * @func 关闭弹窗
     * @desc 点击关闭的回调
     * @param {Function} done - 完成的回调
     * */
    handleClose(done) {
      this.emptyForm();
      // this.$refs['basicForm'].resetForm()
      // this.$refs['toCardForm'].$refs.robBankPositive.clearFiles()
      // this.$refs['toCardForm'].$refs.robBankBack.clearFiles()
      // this.$refs['toCardForm'].$refs.robCardPublicImg.clearFiles()
      // this.$refs['toMainForm'].$refs.roaLicenseImage.clearFiles()
      // this.$refs['toMainForm'].$refs.roaCardPositive.clearFiles()
      // this.$refs['toMainForm'].$refs.roaCardBack.clearFiles()
      this.aisleData = [];
      this.aisleAllot = [];
      this.onLoad(this.page);
      done();
    },
    /**
     * @func 清空
     * @desc OEM表单信息 清空
     * */
    emptyForm() {
      this.$refs['toBasicForm'].$refs['basicForm'].resetFields();
      this.$refs['toMainForm'].$refs['mainForm'].resetFields();
      this.$refs['toCardForm'].$refs['cardForm'].resetFields();
      this.basicForm = {};
      this.mainForm = {};
      this.cardForm = {};

      this.$refs["toBasicForm"].backgroundUrlList = [];
      this.$refs['toMainForm'].roaLicenseFileList = [];
      this.$refs['toMainForm'].roaPositiveFileList = [];
      this.$refs['toMainForm'].roaCardBackFileList = [];
      this.$refs['toCardForm'].robBankFileList = [];
      this.$refs['toCardForm'].robBackFileList = [];
      this.$refs['toCardForm'].robCardFileList = [];
      this.aisleData = [];
      this.aisleAllot = [];
    },
    /**
     * @func 新增
     * @desc 点击新增初始化显示基本信息
     * */
    handleSave() {
      this.active = 0;
      this.dialogVisible = true;
      this.dialogType = 'add';
      this.dialogText = '新增';
      this.dialogSubmitBtnText = '下一页';
    },
    /**
     * @func 编辑
     * @desc 点击编辑回显基本信息
     * @param {Object} row - OEM表格绑定的信息
     * */
    handleEdit(row) {
      this.active = 0;
      this.dialogVisible = true;
      this.dialogType = 'edit';
      this.dialogText = '编辑';
      this.dialogSubmitBtnText = '下一页';
      this.basicDetail(row);
    },
    /**
     * @func 菜单分配
     * @desc 点击编辑回显基本信息
     * @param {Object} row - OEM表格绑定的信息
     * */
    handleMenu(row) {
      this.dialogMenuVisible = true;
      this.$nextTick(() => {
        this.oem.tenantId = row.tenantId;
        this.$refs["toMenuGrant"].getMenuGrant("details", "1", {"userId": row.adminUserId});
      })
    },
    /**
     * @func 详情
     * @desc 点击查看进入详情页
     * @param {Object} row - OEM表格绑定的信息
     * */
    handleView(row) {
      this.$router.push({
        name: "租户详情",
        query: {
          tenantId: row.tenantId
        }
      });
      // this.$set(row, 'formKey', 'wf_ex_oemInvoice')
      // console.log(row, 'row----start')
      // this.dynamicRoute(row, 'start', true);
    },
    menuSubmit() {
      const menuList = this.$refs["toMenuGrant"].$refs.treeMenu.getCheckedKeys();
      const menudata = {
        "tenantId": this.oem.tenantId,
        "menuIds": menuList
      }
      submitMenu(menudata).then((res) => {
        if (res.data.code == '200') {
          this.dialogMenuVisible = false;
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        } else {
          this.$message({
            type: "error",
            message: res.data.message
          });
        }
      }, error => {
        window.console.log(error);
      });
    },
    /**
     * @func OEM基本信息提交
     * @desc 提交基本信息
     * @param {String} type - 类型(新增/修改)
     * */
    basicSubmit(type) {
      if (type === 'add') {
        this.$refs['toBasicForm'].$refs['basicForm'].validate((valid) => {
          if (valid) {
            // const menuList = this.$refs.treeMenu.getCheckedKeys();
            // this.$set(this.basicForm, 'ids', menuList);
            [this.basicForm.province, this.basicForm.city, this.basicForm.area] = this.basicForm.provinceCityArea;
            add(this.basicForm).then((res) => {
              this.oem = res.data.data;
              if (res.data.code == '200') {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            }, error => {
              window.console.log(error);
            });
          } else {
            return false;
          }
        });
      } else if (type === 'edit') {
        this.$refs['toBasicForm'].$refs['basicForm'].validate((valid) => {
          if (valid) {
            // const menuList = this.$refs.treeMenu.getCheckedKeys();
            // this.$set(this.basicForm, 'ids', menuList);
            [this.basicForm.province, this.basicForm.city, this.basicForm.area] = this.basicForm.provinceCityArea;
            update(this.basicForm).then((res) => {
              this.oem = res.data.data;
              if (res.data.code == '200') {
                this.mainDetail(this.oem);
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            }, error => {
              window.console.log(error);
            });
          } else {
            return false;
          }
        });
      }
    },
    /**
     * @func OEM基本信息详情
     * @desc 基本信息详情
     * @param {Object} row - 详情 请求参数
     * */
    basicDetail(row) {
      getDetail(row.id).then(res => {
        const data = res.data.data;
        this.$set(data, 'provinceCityArea', [data.province, data.city, data.area]);
        data.tenantType = data.tenantType.toString();
        data.isCooperate = data.isCooperate.toString();
        data.profitState = data.profitState.toString();
        data.cooperateState = data.cooperateState.toString();
        this.$refs["toBasicForm"].isShow = false;
        this.$nextTick(() => {
          this.$refs["toBasicForm"].isShow = true;
          this.basicForm = data;
          // this.basicForm.provinceCityArea = [this.basicForm.province, this.basicForm.city, this.basicForm.area];
          this.$refs["toBasicForm"].backgroundUrlList.length == 0 && res.data.data.backgroundUrl ? this.$refs["toBasicForm"].backgroundUrlList.push({url: res.data.data.backgroundUrl || ""}) : this.$refs["toBasicForm"].backgroundUrlList;
        });
      });
    },
    /**
     * @func OEM实名信息提交
     * @desc 提交实名信息
     * @param {String} type - 类型(新增/修改)
     * */
    mainSubmit(type) {
      if (type === 'add') {
        this.$refs['toMainForm'].$refs['mainForm'].validate((valid) => {
          if (valid) {
            this.$set(this.mainForm, 'tenantId', this.oem.tenantId);
            this.$set(this.mainForm, 'userNo', this.oem.userNo);
            this.$set(this.mainForm, 'userType', this.oem.userType);

            authAdd(this.mainForm).then((res) => {
              if (res.data.code == '200') {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            }, error => {
              window.console.log(error);
            });
          } else {
            return false;
          }
        });
      } else if (type === 'edit') {
        this.$refs['toMainForm'].$refs['mainForm'].validate((valid) => {
          if (valid) {
            this.$set(this.mainForm, 'tenantId', this.oem.tenantId);
            this.$set(this.mainForm, 'userNo', this.oem.userNo);
            this.$set(this.mainForm, 'userType', this.oem.userType);

            authUpdate(this.mainForm).then((res) => {
              if (res.data.code == '200') {
                this.cardDetail(this.oem);
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            }, error => {
              window.console.log(error);
            });
          } else {
            return false;
          }
        });
      }
    },
    /**
     * @func OEM实名信息详情
     * @desc 实名信息 详情
     * @param {Object} oem - 详情 请求参数
     * */
    mainDetail(oem) {
      getAuthDetail(oem.tenantId, oem.userNo, oem.userType).then(res => {
        this.mainForm = res.data.data;
        if (JSON.stringify(res.data.data) !== '{}') {
          this.$refs["toMainForm"].roaLicenseFileList.length == 0 && res.data.data.roaLicenseImageUrl ? this.$refs["toMainForm"].roaLicenseFileList.push({url: res.data.data.roaLicenseImageUrl || ""}) : this.$refs["toMainForm"].roaLicenseFileList;
          this.$refs["toMainForm"].roaPositiveFileList.length == 0 && res.data.data.roaCardPositiveUrl ? this.$refs["toMainForm"].roaPositiveFileList.push({url: res.data.data.roaCardPositiveUrl || ""}) : this.$refs["toMainForm"].roaPositiveFileList;
          this.$refs["toMainForm"].roaCardBackFileList.length == 0 && res.data.data.roaCardBackUrl ? this.$refs["toMainForm"].roaCardBackFileList.push({url: res.data.data.roaCardBackUrl || ""}) : this.$refs["toMainForm"].roaCardBackFileList;
        }
      });
    },
    /**
     * @func OEM结算卡提交
     * @desc 提交结算卡信息
     * @param {String} type - 类型(新增/修改)
     * */
    cardSubmit(type) {
      this.aisleData = [];
      if (type === 'add') {
        this.$refs['toCardForm'].$refs['cardForm'].validate((valid) => {
          if (valid) {
            this.$set(this.cardForm, 'tenantId', this.oem.tenantId);
            this.$set(this.cardForm, 'userNo', this.oem.userNo);
            this.$set(this.cardForm, 'userType', this.oem.userType);
            bankAdd(this.cardForm).then((res) => {
              if (res.data.code == '200') {
                getAisleAllList('-1', '-1', this.oem.userNo, this.oem.userType).then(res => {
                  let aisleData = res.data.data.records;
                  aisleData.forEach((item, index) => {
                    this.aisleData.push({
                      label: item.aisleName,
                      key: item.aisleCode,
                      pinyin: item.aisleAlias[index]
                    });
                  });
                });
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            }, error => {
              window.console.log(error);
            });
          } else {
            return false;
          }
        });
      } else if (type === 'edit') {
        this.$refs['toCardForm'].$refs['cardForm'].validate((valid) => {
          if (valid) {
            this.aisleAllot = [];
            this.$set(this.cardForm, 'tenantId', this.oem.tenantId);
            this.$set(this.cardForm, 'userNo', this.oem.userNo);
            this.$set(this.cardForm, 'userType', this.oem.userType);
            bankUpdate(this.cardForm).then((res) => {
              if (res.data.code == '200') {
                getAisleAllList('-1', '-1', this.oem.userNo, this.oem.userType).then(res => {
                  let aisleData = res.data.data.records;
                  aisleData.forEach((item, index) => {
                    this.aisleData.push({
                      label: item.aisleName,
                      key: item.aisleCode,
                      pinyin: item.aisleAlias[index]
                    });
                  });
                });
                getAisleOemList(this.oem.tenantId, this.oem.userNo, this.oem.userType).then(res => {
                  let aisleAllots = res.data.data.records;
                  aisleAllots.forEach((item) => {
                    this.aisleAllot.push(item.aisleCode);
                  });
                });
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            }, error => {
              window.console.log(error);
            });
          }
        });
      }
    },
    /**
     * @func OEM结算卡详情
     * @desc 结算卡信息 详情
     * @param {Object} oem - 详情 请求参数
     * */
    cardDetail(oem) {
      getBankDetail(oem.tenantId, oem.userNo, oem.userType).then(res => {
        this.cardForm = res.data.data;
        if (JSON.stringify(res.data.data) !== '{}') {
          // this.$refs["toCardForm"].robBankFileList.length == 0 && res.data.data.robBankPositiveUrl ? this.$refs["toCardForm"].robBankFileList.push({url: res.data.data.robBankPositiveUrl || ""}) : this.$refs["toCardForm"].robBankFileList;
          // this.$refs["toCardForm"].robBackFileList.length == 0 && res.data.data.robBankBackUrl ? this.$refs["toCardForm"].robBackFileList.push({url: res.data.data.robBankBackUrl || ""}) : this.$refs["toCardForm"].robBackFileList;
          this.$refs["toCardForm"].robCardFileList.length == 0 && res.data.data.robCardPublicImgUrl ? this.$refs["toCardForm"].robCardFileList.push({url: res.data.data.robCardPublicImgUrl || ""}) : this.$refs["toCardForm"].robCardFileList;
        }
      });
    },
    /**
     * @func OEM通道提交
     * @desc 根据可选通道分配通道提交
     * @param {String} type - 类型(新增/修改)
     * */
    aisleSubmit(type) {
      if (this.aisleAllot.length > 0) {
        if (type === 'add') {
          let aisleDatas = {
            "aisleCodes": this.aisleAllot,
            ...this.oem
          }
          aisleAdd(aisleDatas).then((res) => {
            if (res.data.code == '200') {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              if (this.active++ > 4) this.active = 0;
            } else {
              this.$message({
                type: "error",
                message: res.data.message
              });
            }
          }, error => {
            window.console.log(error);
          });
        } else if (type === 'edit') {
          let aisleDatas = {
            "aisleCodes": this.aisleAllot,
            ...this.oem
          }
          aisleUpdate(aisleDatas).then((res) => {
            if (res.data.code == '200') {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              if (this.active++ > 4) this.active = 0;
            } else {
              this.$message({
                type: "error",
                message: res.data.message
              });
            }
          }, error => {
            window.console.log(error);
          });
        } else {
          return false;
        }
      } else {
        this.$message({
          type: "warning",
          message: "请先选择通道!"
        });
      }
    },
    /**
     * @func OEM政策分润提交
     * @desc 根据已分配通道处理政策阶梯分润提交
     * @param {String} type - 类型(新增/修改)
     * */
    oemPolicySubmit(type) {
      if (type === 'add') {
        let policyDatas = {
          "aisleList": this.$refs['toPolicyForm'].data,
          ...this.oem
        }
        oemPolicyAdd(policyDatas).then((res) => {
          if (res.data.code == '200') {
            getFinish(this.oem.tenantId).then((fini) => {
              if (fini.data.code == '200') {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                if (this.active++ > 4) this.active = 0;
                this.dialogSubmitBtnText = '提 交';
                this.getAllDetails(this.oem.tenantId);
              }
            }, error => {
              window.console.log(error);
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.message
            });
          }
        }, error => {
          window.console.log(error);
        });
      } else if (type === 'edit') {
        let policyDatas = {
          "aisleList": this.$refs['toPolicyForm'].data,
          ...this.oem
        }
        oemPolicyUpdate(policyDatas).then((res) => {
          if (res.data.code == '200') {
            getFinish(this.oem.tenantId).then((fini) => {
              if (fini.data.code == '200') {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                if (this.active++ > 4) this.active = 0;
                this.dialogSubmitBtnText = '提 交';
                this.getAllDetails(this.oem.tenantId);
              }
            }, error => {
              window.console.log(error);
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.message
            });
          }
        }, error => {
          window.console.log(error);
        });
      }
    },
    /* 租户详情接口 */
    getAllDetails(tenantId) {
      getTenantDetail(tenantId).then((res) => {
        let data = res.data.data;
        data.baseInfo.tenantType = data.baseInfo.tenantType + "";
        data.baseInfo.isCooperate = data.baseInfo.isCooperate + "";
        data.baseInfo.cooperateState = data.baseInfo.cooperateState + "";
        data.baseInfo.profitState = data.baseInfo.profitState + "";
        data.baseInfo.provinceCityArea = [
          data.baseInfo.province,
          data.baseInfo.city,
          data.baseInfo.area,
        ];
        this.$nextTick(()=>{
          this.tenantData = data;
        })
      });
    },
    rowSave(row, done, loading) {
      //合同等状态 初始化赋值
      row.isCooperate = this.form.isCooperate;
      row.profitState = this.form.profitState;
      row.cooperateState = this.form.cooperateState;
      // const menuList = this.$refs.treeMenu.getCheckedKeys();
      // row.ids = menuList;
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      // const menuList = this.$refs.treeMenu.getCheckedKeys();
      // row.ids = menuList;
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    /**
     * @func dialog打开回调
     * @desc 监听回调类型，调取接口，处理逻辑
     * @param {Function} done - 回调完成
     * @param {String} type - 打开类型
     * */
    beforeOpen(done, type) {
      if (["view", "edit"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   const data = res.data.data;
        //   if (["view"].includes(type)) {
        //     if (!(data.accountNumber > 0)) {
        //       data.accountNumber = "不限制";
        //     }
        //     if (!data.expireTime) {
        //       data.expireTime = "不限制";
        //     }
        //   }
        //   this.form = data;
        // });
      } else if (["add"].includes(type)) {
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleSetting() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      if (this.selectionList.length === 1) {
        getDetail(this.selectionList[0].id).then(res => {
          const data = res.data.data;
          this.settingForm.accountNumber = data.accountNumber;
          this.settingForm.expireTime = data.expireTime;
          this.settingForm.isCooperate = data.isCooperate;
          this.settingForm.profitState = data.profitState;
          this.settingForm.cooperateState = data.cooperateState;
        });
      } else {
        this.settingForm.accountNumber = -1;
        this.settingForm.expireTime = '';
      }
      this.box = true;
    },
    handleDatasource() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      if (this.selectionList.length !== 1) {
        this.$message.warning("只能选择一条数据");
        return;
      }
      getDetail(this.selectionList[0].id).then(res => {
        const data = res.data.data;
        this.datasourceForm.datasourceId = data.datasourceId;
      });
      this.datasourceBox = true;
    },
    handlePackage() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      if (this.selectionList.length !== 1) {
        this.$message.warning("只能选择一条数据");
        return;
      }
      if (this.selectionList.length === 1) {
        packageInfo(this.selectionList[0].id).then(res => {
          const data = res.data.data;
          this.packageForm.packageId = data.id;
          this.packageForm.menuId = data.menuId;
        });
      } else {
        this.packageForm.menuId = '';
      }
      this.packageBox = true;
      //更新字典远程数据
      setTimeout(() => {
        const form = this.$refs.formPackage;
        form.updateDic('packageId');
      }, 10);
    },
    handlePackageSetting() {
      this.packageSettingBox = true;
    },
    handleSubmit(form, done, loading) {
      setting(this.ids, form).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "配置成功!"
        });
        done();
        this.box = false;
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    handleDatasourceSubmit(form, done, loading) {
      datasource(this.tenantId, form.datasourceId).then(() => {
        this.$message({
          type: "success",
          message: "配置成功!"
        });
        done();
        this.datasourceBox = false;
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    handlePackageSubmit(form, done, loading) {
      packageSetting(this.tenantId, form.packageId).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "配置成功!"
        });
        done();
        this.packageBox = false;
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
// /deep/.el-dialog {
//   max-height: 96%;
//   margin-top: 0;
//   margin-bottom: 0;
//   overflow: auto;
// }
// /deep/.el-dialog__header {
//   position: sticky;
//   top: 0;
//   background: #FFFFFF;
//   z-index: 999;
//   transition: all 1s linear;
// }
// /deep/.el-dialog__footer {
//   position: sticky;
//   bottom: 0;
//   background: #FFFFFF;
//   box-shadow: 0px 0px 9px 0px rgba(48, 48, 48, 0.1);
//   z-index: 999;
// }

// .dialog-menu {
//   position: sticky;
//   top: 54px;
//   background: #FFFFFF;
//   z-index: 999;
//   transition: all 1s linear;
// }

.tenant-flex {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

/deep/.el-transfer-panel__list.is-filterable{
  width: 400px !important;
  height: 500px !important;
}

/deep/.el-transfer-panel{
  width: 400px !important;
  height: 500px !important;
}
/deep/ .el-tag--dark.el-tag--success {
  border-color: transparent;
  opacity: 0.8;
}
</style>
